package com.lnsoft.dqfs.server.handle.threadpools;

import com.lnsoft.dqfs.server.handle.codec.Frame;
import com.lnsoft.dqfs.server.util.Arrays16;
import io.netty.channel.ChannelHandlerContext;
import lombok.Builder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentLinkedDeque;


@Slf4j
public class SleepReadArgCommon {
    private static final SleepReadArgCommon instance = new SleepReadArgCommon();
    private Deamon deamon;
    private SleepReadArgCommon(){
        deamon = new Deamon();
        deamon.setDaemon(true);
        deamon.setName("sleep-readArg-thread");
        deamon.start();
        log.info("sleep-readArg-thread 启动");
    }

    public static SleepReadArgCommon getInstance(){
        return instance;
    }

    public void push(ReadArgCls cls){
        deamon.push(cls);
    }

    @Builder
    @Getter
    public static class ReadArgCls{
        private ChannelHandlerContext ctx;
        private Frame frame;
        private byte[] readArgFrame;
        private long time;
    }


    private class Deamon extends Thread{

        private  final ConcurrentLinkedDeque<ReadArgCls> deque = new ConcurrentLinkedDeque<>();

        public void push(ReadArgCls cls){
            deque.offer(cls);
        }

        @Override
        public void run() {
            log.info("sleep-readArg-thread 线程 start");
            while (true) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                while (true) {
                    ReadArgCls cls = deque.poll();
                    if(cls==null){
                        break;
                    }

                    if ((System.currentTimeMillis() - cls.time) < 30 * 1000) {
                        if(cls!=null){
                            deque.addFirst(cls);
                        }
                        log.debug("没有小于30秒的读取任务 break");
                        break;
                    }
                    cls.getFrame().setUpServerFcb(true);
                    cls.getCtx().writeAndFlush(cls.getReadArgFrame());
                    log.debug("服务端请求获取客户端版本号{}:{}报文:{}",  cls.getFrame().getClientName(), cls.getFrame().getServerPort(), Arrays16.toString(cls.getReadArgFrame()));

                }
            }
        }
    }

}
